package com.itheima.health.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.mobile.utils.SMSUtils;
import com.itheima.health.pojo.Order;
import com.itheima.health.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @Author likepei
 * @Date 2020/1/31 16:47
 * @Version v1.0
 * @Description 预约订单
 */
@RestController
@RequestMapping("/mobile/order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;
    @Reference
    private OrderService orderService;

    /**
     * 根据ID查询预约信息
     * @param id 订单ID
     * @return
     */
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Result result = orderService.findById4Detail(id);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.QUERY_ORDER_FAIL);
        }
    }

    /**
     * 保存预约订单
     * 步骤:
     * 1.验证短信验证码
     * 2.调用Service完成订单保存
     * 3.预约成功短信通知预约人
     *
     * @param map 表单数据
     */
    @RequestMapping("/submit")
    public Result subimtOrder(@RequestBody Map<String, String> map){
        System.out.println("map = " + map);
        //验证短信验证码
        //1.从前端获取验证码
        String telephone = map.get("telephone");
        String validateCode = map.get("validateCode");
        //2.从redis获取验证码
        String orderInRedis = jedisPool.getResource().get(telephone + RedisConst.SENDTYPE_ORDER);
        System.out.println("telephone = "+ telephone +" ,validateCode="+ validateCode +" ,orderInRedis="+ orderInRedis);
        //3.进行比对校验
        if(orderInRedis == null || !orderInRedis.equals(validateCode)){
            return new Result(false, MessageConst.VALIDATECODE_ERROR);
        }
        Result result = null;
        try {
            //调用Service完成订单保存
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            result = orderService.addOrder(map);
            //发送预约完成的短信通知
            /*
            if (result.getFlag()){
                String orderDate = map.get("orderDate");
                SMSUtils.sendShortMessage(telephone, orderDate);
            }
            */
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }
}
